package com.xyhuo.leetcode.june;

import java.util.HashMap;
import java.util.Map;

/**
 * 169. 多数元素
 * https://leetcode.cn/problems/majority-element/description/
 */
public class MajorityElement {

    public int majorityElement(int[] nums) {
        Map<Integer, Integer> numCountMap = new HashMap<>();
        for (int num : nums) {
            int value = 1;
            if (numCountMap.containsKey(num)) {
                value += numCountMap.get(num);
            }
            numCountMap.put(num, value);
        }
        int middle = nums.length / 2;
        for (Map.Entry<Integer, Integer> item : numCountMap.entrySet()) {
            if (item.getValue() > middle) {
                return item.getKey();
            }
        }
        return -1;
    }
}
